package com.cmcc.linlaker.ui.upload.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.cmcc.linlaker.LoadingActivity;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.application.LinhuApp;
import com.cmcc.linlaker.bean.BaseBean;
import com.cmcc.linlaker.bean.ImageUploadBean;
import com.cmcc.linlaker.fragment.RoundFragment;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.permission.GPermisson;
import com.cmcc.linlaker.permission.PermissionCallback;
import com.cmcc.linlaker.ui.query.ImageScanActivity;
import com.cmcc.linlaker.ui.upload.UploadSelfDealDetailActivity;
import com.cmcc.linlaker.ui.upload.UploadSuccessActivity;
import com.cmcc.linlaker.ui.upload.adapter.ImageAdapter;
import com.cmcc.linlaker.ui.upload.bean.ImageBean;
import com.cmcc.linlaker.utils.DensityUtil;
import com.cmcc.linlaker.utils.IntentUtils;
import com.cmcc.linlaker.utils.PhotoUtils;
import com.cmcc.linlaker.utils.PictureUtil;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.StringUtils;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.utils.Utils;
import com.cmcc.linlaker.view.GridSpacingItemDecoration;
import com.cmcc.linlaker.volley.GsonRequestHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.tianditu.android.maps.GeoPoint;
import com.tianditu.android.maps.MapView;
import com.tianditu.android.maps.MyLocationOverlay;
import com.tianditu.android.maps.OnGetPoiResultListener;
import com.tianditu.android.maps.PoiInfo;
import com.tianditu.android.maps.PoiSearch;
import com.tianditu.android.maps.TErrorCode;
import com.tianditu.android.maps.TGeoAddress;
import com.tianditu.android.maps.TGeoDecode;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zyyoona7.wheel.WheelView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class UploadOtherFragment extends Fragment {
    private View fragmentView;

    public static UploadOtherFragment newInstance() {
        UploadOtherFragment fragment = new UploadOtherFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.fragment_upload_other, container, false);
        initView();
        return fragmentView;
    }

    private ImageAdapter adapter;
    private List<ImageBean> bmpList = new ArrayList<>();
    private RecyclerView recycler_pic;

    private TextView text_project_name, text_input_info;
    private EditText edit_address, edit_title, edit_description;

    private void initView() {
        recycler_pic = fragmentView.findViewById(R.id.recycler_pic);
        setRecyclerView(recycler_pic, bmpList);

        addButton();

        text_input_info = fragmentView.findViewById(R.id.text_input_info);
        edit_address = fragmentView.findViewById(R.id.edit_address);
        text_project_name = fragmentView.findViewById(R.id.text_project_name);
        edit_title = fragmentView.findViewById(R.id.edit_title);
        edit_description = fragmentView.findViewById(R.id.edit_description);
        edit_description.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String content = edit_description.getText().toString();
                int length = content.length();
                text_input_info.setText(length + "/100");
            }
        });
        fragmentView.findViewById(R.id.layoutConnectedProject).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDict(fragmentView.findViewById(R.id.layout_upload));
            }
        });
        fragmentView.findViewById(R.id.text_upload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upload();
            }
        });
        fragmentView.findViewById(R.id.layout_address_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLocationInfo();
            }
        });

//        getProblemNumber();
    }


    /**
     * 上报
     */
    public void upload() {
        String address = edit_address.getText().toString();
        if (latitude != 0 && longitude != 0) {
            uploadData();
        } else {
            getLatLng(address);
        }

    }


    private void setRecyclerView(final RecyclerView recycler_view, final List<ImageBean> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new GridLayoutManager(getActivity(), 4));

        recycler_view.setNestedScrollingEnabled(false);
        recycler_view.addItemDecoration(new GridSpacingItemDecoration(4, DensityUtil.dip2px(getActivity(), 10), true));
        adapter = new ImageAdapter(getActivity(), itemList);
        adapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (itemList.get(position).type == 0) {
                    selectPictures();
                } else {
                    Intent intent = new Intent(getActivity(), ImageScanActivity.class);
                    intent.putExtra("imageList", imageList);
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }

            @Override
            public void onItemDeleteClick(int position) {
                deletePic(position);
            }
        });
        recycler_view.setAdapter(adapter);
    }

    /**
     * 选择图片
     */
    public void selectPictures() {
        if (Build.VERSION.SDK_INT >= 23) {
            GPermisson.with(getActivity())
                    .permisson(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
                    .callback(new PermissionCallback() {
                        @Override
                        public void onPermissionGranted() {
                            showSelectDialog();
                        }

                        @Override
                        public void shouldShowRational(String permisson) {
                        }

                        @Override
                        public void onPermissonReject(String permisson) {
                        }
                    }).request();
        } else {
            showSelectDialog();
        }

    }

    private void showSelectDialog() {
        final String[] items = {"相机", "相册"};
        AlertDialog.Builder builder = new AlertDialog.Builder(
                getActivity());
        builder.setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (which == 0) {// 相机
                            takePhoto();
                        } else if (which == 1) {// 相册
                            choosePhoto();
                        }

                    }
                }).create().show();
    }

    public static final int RC_TAKE_PHOTO = 1;
    public static final int RC_CHOOSE_PHOTO = 2;
    public static final int RC_CROP_PHOTO = 3;

    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;

    /**
     * 拍照
     */
    private void takePhoto() {
        imageUri = Uri.fromFile(fileUri);
        //通过FileProvider创建一个content类型的Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(getActivity(), "com.cmcc.linlaker.fileprovider", fileUri);
        }

        PhotoUtils.fragmentTakePicture(this, imageUri, RC_TAKE_PHOTO);
    }

    /**
     * 打开相册
     */
    private void choosePhoto() {
        PhotoUtils.fragmentOpenPic(this, RC_CHOOSE_PHOTO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == RC_TAKE_PHOTO) {
                cropImageUri = Uri.fromFile(fileCropUri);

                PhotoUtils.fragmentCropImageUri(this, imageUri, cropImageUri, 1, 1, LoadingActivity.screenWidth, LoadingActivity.screenWidth, RC_CROP_PHOTO);
            } else if (requestCode == RC_CHOOSE_PHOTO) {
                cropImageUri = Uri.fromFile(fileCropUri);
                Uri newUri = Uri.parse(PhotoUtils.getPath(getActivity(), data.getData()));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    newUri = FileProvider.getUriForFile(getActivity(), "com.cmcc.linlaker.fileprovider", new File(newUri.getPath()));
                }

                PhotoUtils.fragmentCropImageUri(this, newUri, cropImageUri, 1, 1, LoadingActivity.screenWidth, LoadingActivity.screenWidth, RC_CROP_PHOTO);
            } else if (requestCode == RC_CROP_PHOTO) {
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(cropImageUri, getActivity());

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp(myBitmap);

                uploadPic(fileName + ".png", file);
            }
        } else if (resultCode == 100) {
            getActivity().finish();
        } else if (resultCode == 200) {
            //重置内容
            text_project_name.setText("");
            edit_address.setText("");
            edit_title.setText("");
            edit_description.setText("");

            latitude = 0;
            longitude = 0;

            imageList.clear();
            bmpList.clear();
            adapter.notifyDataSetChanged();

        }
    }

    private ArrayList<String> imageList = new ArrayList<>();

    private void uploadPic(String fileName, File file) {
        Map<String, String> headers = new HashMap<>();
        headers.put("authToken", SPHelper.getAuthToken());
        headers.put("from", "android");
        OkHttpUtils.post()
                .headers(headers)
                .addFile("file", fileName, file)
                .url(ApiDefine.UPLOAD_PIC)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("onError:", "onError");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("url:", response);
                        String jsonStr = response;
                        Gson gson = new GsonBuilder().create();
                        ImageUploadBean bean = gson.fromJson(jsonStr, new TypeToken<ImageUploadBean>() {
                        }.getType());

                        if (bean != null) {
                            imageList.add(bean.url);
                        }

                    }
                });
    }

    /**
     * 删除图片
     */
    private void deletePic(int position) {
        imageList.remove(position);
        bmpList.remove(position);

        adapter.notifyDataSetChanged();
    }

    /**
     * 添加按钮
     */
    private void addButton() {
        ImageBean bean = new ImageBean();
        bean.type = 0;
        bmpList.add(bean);

        adapter.notifyDataSetChanged();
    }

    /**
     * 添加图片
     */
    private void addBmp(Bitmap bmp) {
        ImageBean bean = new ImageBean();
        bean.bitmap = bmp;
        bean.path = StringUtils.bitmaptoString(bmp);
        bean.type = 1;
        bmpList.add(bmpList.size() - 1, bean);

        adapter.notifyDataSetChanged();
    }


    private GeoPoint geoPoint;
    private double latitude, longitude;


    private void initLocation() {
        geoPoint = RoundFragment.mMyLocation.getMyLocation();

        latitude = geoPoint.getLatitudeE6();
        longitude = geoPoint.getLongitudeE6();

        //逆地理编码类，根据输入的点坐标，返回相应的地理信息
        TGeoDecode tGeoDecode = new TGeoDecode(new OnGeoResultListener());
        tGeoDecode.search(geoPoint);
    }

    class MyOverlay extends MyLocationOverlay {
        public MyOverlay(Context context, MapView mapView) {
            super(context, mapView);
        }

        /*
         * 处理在"我的位置"上的点击事件
         */
        protected boolean dispatchTap() {
            return true;
        }

        @Override
        public void onLocationChanged(Location location) {
            super.onLocationChanged(location);
        }
    }

    /**
     * 逆地理编码回调结果监听
     */
    class OnGeoResultListener implements TGeoDecode.OnGeoResultListener {

        @Override
        public void onGeoDecodeResult(TGeoAddress tGeoAddress, int errorCode) {

            if (TErrorCode.OK == errorCode) {
                // 查询点相关信息
                edit_address.setText(tGeoAddress.getFullName());
            } else {
                ToastUtils.showText(getActivity(), "位置查询出错，请稍后重试");
            }
        }
    }

    /**
     * 获取定位
     */
    public void getLocationInfo() {
        initLocation();
    }

    private PoiSearch mPoiSearch;

    /**
     * 根据地址查询经纬度
     */
    private void getLatLng(String address) {
        mPoiSearch = new PoiSearch(getActivity(), new OnGetPoiResultListener() {
            @Override
            public void OnGetPoiResult(ArrayList<PoiInfo> arrayList, ArrayList<PoiSearch.ProvinceInfo> arrayList1, String s, int i) {
                if (arrayList != null && arrayList.size() > 0) {
                    longitude = arrayList.get(0).mPoint.getLongitudeE6();
                    latitude = arrayList.get(0).mPoint.getLatitudeE6();

                    uploadData();
                } else {
                    ToastUtils.showText(getActivity(), "请输入正确的地址信息");
                    edit_address.requestFocus();
                    Utils.showSoftInputFromWindow(edit_address);
                }
            }
        }, RoundFragment.mMapView);
        mPoiSearch.search(address, null, null);
    }


    /**
     * 获取图片url
     */
    private String getImageListStr() {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < imageList.size(); i++) {
            if (i < imageList.size() - 1) {
                stringBuffer.append(imageList.get(i) + ",");
            } else {
                stringBuffer.append(imageList.get(i));
            }
        }

        return stringBuffer.toString();
    }

    /**
     * 获取问题编号
     */
    private void getProblemNumber() {
        GsonRequestHelper helper = new GsonRequestHelper(getActivity());
        Map<String, String> params = new HashMap<>();

        helper.sendPOSTRequest(ApiDefine.GETNUMBER, BaseBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    BaseBean bean = (BaseBean) data;

                    if (bean.code.equals("0")) {
//                        text_serialNumber.setText(bean.msg);
                    } else {
                    }
                }
            }
        });
    }

    /**
     * 新增
     */
    private void uploadData() {
        if (TextUtils.isEmpty(edit_title.getText().toString())) {
            ToastUtils.showText(getActivity(), "请输入台账标题");
            edit_title.requestFocus();
            Utils.showSoftInputFromWindow(edit_title);
            return;
        }

        if (TextUtils.isEmpty(edit_address.getText().toString())) {
            ToastUtils.showText(getActivity(), "请输入地址");
            edit_address.requestFocus();
            Utils.showSoftInputFromWindow(edit_address);
            return;
        }

        if (TextUtils.isEmpty(text_project_name.getText().toString())) {
            ToastUtils.showText(getActivity(), "请选择问题类别");
            return;
        }

        GsonRequestHelper helper = new GsonRequestHelper(getActivity());
        Map<String, String> params = new HashMap<>();
        params.put("reportPlace", edit_address.getText().toString());
        params.put("description", edit_description.getText().toString());
//        params.put("latitude", Utils.formatLatLng((float) (latitude / 1E6)));
//        params.put("longitude", Utils.formatLatLng((float) (longitude / 1E6)));
        params.put("latitude", latitude + "");
        params.put("longitude",longitude + "");
        Log.e("latitude", Utils.formatLatLng((float) (latitude / 1E6)));
        Log.e("longitude", Utils.formatLatLng((float) (longitude / 1E6)));
        params.put("photographer", SPHelper.getUid());
        params.put("problemSort", "2");
        params.put("problemType", LinhuApp.problemTypeList.get(problemTypePos).dictValue);

        params.put("title", edit_title.getText().toString());
        params.put("problemPhotoUrls", getImageListStr());
        params.put("description", edit_description.getText().toString());

        helper.sendPOSTRequest(ApiDefine.PROBLEM_ADD, BaseBean.class, params, true, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    BaseBean bean = (BaseBean) data;

                    if (bean.code.equals("0")) {
                        Intent intent = new Intent(getActivity(), UploadSuccessActivity.class);
                        startActivityForResult(intent, 100);
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(getActivity());
                    } else {
                        ToastUtils.showText(getActivity(), bean.msg);
                    }
                }
            }
        });
    }


    private int problemTypePos;
    private PopupWindow popupWindow;

    private void showDict(View view) {
        if (popupWindow != null && popupWindow.isShowing()) {
            return;
        }
        RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.pop_dict, null);
        popupWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getActivity().getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getActivity().getWindow().setAttributes(lp);


        //点击空白处时，隐藏掉pop窗口
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
        popupWindow.setAnimationStyle(R.style.Popupwindow3);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.BOTTOM, 0, -location[1]);
        //添加按键事件监听
        setButtonListeners(layout);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getActivity().getWindow().setAttributes(lp);
            }
        });
    }

    private void setButtonListeners(RelativeLayout layout) {
        TextView text_cancel = layout.findViewById(R.id.text_cancel);
        TextView text_ok = layout.findViewById(R.id.text_ok);
        final WheelView wheelview = layout.findViewById(R.id.wheelview);

        text_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        text_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

                problemTypePos = wheelview.getSelectedItemPosition();
                text_project_name.setText(LinhuApp.problemTypeList.get(problemTypePos).dictLabel);
            }
        });

        wheelview.setData(LinhuApp.problemTypeList);

        //尽请使用各种方法
        wheelview.setTextSize(20f, true);
        wheelview.setNormalItemTextColor(0xff666666);
        wheelview.setSelectedItemTextColor(0xff000000);
        wheelview.setDividerPaddingForWrap(13f);

        wheelview.setSelectedItemPosition(problemTypePos);
    }
}
